<?php

namespace App\Models;


use App\Traits\HasDateTimeFormatter;
use App\Traits\Ownable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
    use HasDateTimeFormatter, Ownable;

    const PAYING = 0; // 支付中
    const SUCCESS = 1; // 已支付
    const TIMEOUT = 2; // 过期未支付
    const FAIL = 3; // 支付失败


    protected $table = 'order';

    protected $casts = [
        'user_id' => 'integer',
        'category' => 'integer',
        'status' => 'integer',
        'price' => 'float',
        'ticket' => 'integer',
        'channel' => 'integer',
    ];

    protected $appends = ['status_name', 'channel_name'];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function org() {
        return $this->hasOne(Org::class, 'org_code', 'org_code');
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function orgRoot() {
        return $this->hasOne(Org::class, 'org_code', 'org_root');
    }

    /**
     */
    protected function statusName(): Attribute
    {
        return Attribute::make(
            get: function ($value, $attributes) {
                $def = [
                    self::PAYING => '支付中',
                    self::SUCCESS => '已支付',
                    self::TIMEOUT => '过期未支付',
                    self::FAIL => '支付失败'
                ];

                return $def[$attributes['status']] ?? '';
            },
        );
    }

    /**
     */
    protected function channelName(): Attribute
    {
        return Attribute::make(
            get: function ($value, $attributes) {
                $def = [
                    0 => '余额',
                    1 => '微信',
                ];

                return $def[$attributes['channel']] ?? '';
            },
        );
    }
}
